// pages/accountBook/accountBook.js
const db = wx.cloud.database()
Page({
  data: {
    books: []
  },

  onLoad() {
    this.loadBooks()
  },

  loadBooks() {
    wx.showLoading({ title: '加载中' })
    wx.cloud.callFunction({
      name: 'loadAccountBook',
      success: res => {
        console.log('账本数据:',res.result)
        this.setData({
          books: res.result.data.map(item => ({
            id: item._id,
            icon: this.getBookIcon(item.type.name),
            typeName: item.type.name,
            name: item.name,
            count: item.records?.length || 0
          }))
        })
      },
      fail: () => wx.showToast({ title: '加载失败', icon: 'none' }),
      complete: () => wx.hideLoading()
    })
  },

  getBookIcon(type) {
    const icons = {
      '日常开销': '../../images/book/rc.jpg',
      '旅行记录': '../../images/book/lx.jpg',
      '恋爱基金': '../../images/book/jt.jpg',
      '学习投资': '../../images/book/xy.jpg',
      '其他': '../../images/book/zx.jpg'
    }
    return icons[type] || '../../images/book/rc.jpg'
  },

  createBook() {
    wx.navigateTo({
      url: '/pages/createAccountBook/createAccountBook',
      events: {
        refreshBooks: () => this.loadBooks()
      }
    })
  }
})